<template>
  <div class="dia">
    <el-dialog
      v-el-drag-dialog
      :title="title"
      :visible.sync="visible"
      width="1024px"
      :before-close="handleClose"
      @closed="reset"
    >
      <div class="btn-col">
        <el-button v-for="i in btnList" :key="i.id" type="primary" :icon="i.icon" @click="onPush(i.id)">{{ i.txt }}</el-button>
      </div>
      <div class="ext-table">
        <el-card v-for="(item, index) in cardList" :key="item.orderNo" :shadow="isStyleId === item.orderNo ? 'always' : 'never'" style="margin-bottom: 20px;" :body-style="isStyleId === item.orderNo ? bodyStyle : '' " @click.native="onBox(item)">
          <template v-if="item.endEdit">
            <div class="card-title">
              <h2 class="title-text" :title="item.itemName">{{ item.itemName }}</h2>
              <div class="card-title-btn">
                <el-button v-for="i in btnsList" :key="i.id" @click.stop="toPush(item, i.id, index)">{{ i.txt }}</el-button>
              </div>
            </div>
            <div class="card-item-class">
              <div><span>分类：</span><span>{{ item.checkTypeName || '' }}</span></div>
              <el-checkbox :checked="item.isShow === 1" disabled>统计展示</el-checkbox>
              <el-checkbox :checked="item.intentionType === 2" disabled>是否有意向</el-checkbox>
            </div>
            <div class="edit-table-tab">
              <!-- <lb-table
                ref="lbTable"
                border
                highlight-current-row
                element-loading-text="加载中"
                :column="tableData.column"
                :data="item.detailList"
              /> -->
              <div v-if="item.itemType === -1">
                <el-radio v-model="item.detailList[0].isChecked" label="必传" disabled>{{ item.detailList[0].itemDetailName }}</el-radio>
                <el-radio v-model="item.detailList[0].isChecked" label="非必传" disabled>{{ item.detailList[1].itemDetailName }}</el-radio>
                <span v-if="item.detailList[1].tips">提示文字：{{ item.detailList[1].tips }}</span>
              </div>
              <el-table
                v-else
                ref="lbTable"
                border
                highlight-current-row
                element-loading-text="加载中"
                :data="item.detailList"
                style="width: 100%;"
              >
                <el-table-column prop="itemDetailName" label="选项说明" />
                <el-table-column prop="csmName" label="默认">
                  <template slot-scope="scope">
                    <div>
                      <el-checkbox v-if="scope.row.itemType === 3" :checked="scope.row.isChecked===2" disabled />
                      <el-radio v-if="scope.row.itemType === 1" v-model="scope.row.isChecked" :label="2" disabled>{{ '' }}</el-radio>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="csmName" label="是否拍照取证">
                  <template slot-scope="scope">
                    <div>
                      <el-checkbox :checked="scope.row.isUploadPic===2" disabled>{{ '' }}</el-checkbox>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="csmName" label="即查即改">
                  <template slot-scope="scope">
                    <div>
                      <el-radio v-if="scope.row.itemType === 1" v-model="scope.row.modificationType" :label="2" disabled>{{ '' }}</el-radio>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
          <template v-else>
            <!-- 编辑组件 -->
            <EditTable ref="edittable" :check-type-list="checkTypeList" @cancelEdit="cancelEdit" @saveEdit="saveEdit" />
          </template>
        </el-card>
        <el-card v-if="isNewCrad" :shadow="isNewCrad ? 'always' : 'never'" :body-style="bodyStyle">
          <!-- 编辑组件 -->
          <EditTable ref="edittable" :check-type-list="checkTypeList" @cancelEdit="cancelEdit" @saveEdit="saveEdit" />
        </el-card>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">
          关闭
        </el-button>
        <el-button :loading="$loadingPlugin.add" type="primary" @click="success">
          保存
        </el-button>
      </div>
    </el-dialog>
    <CopyAdd ref="copyadd" @onCopyAdd="copySave" />
  </div>
</template>

<script>
  import { checkConfigInquire2, checkConfigList, checkConfigSave, gasCheckQueryList } from '@/api'
  import EditTable from './EditTable'
  import CopyAdd from './CopyAdd'

  export default {
    name: 'waterconfig',
    components: {
      EditTable,
      CopyAdd
    },
    data() {
      return {
        btnList: [
          { icon: 'el-icon-circle-plus-outline', txt: '新增', id: 1 },
          { icon: 'el-icon-circle-plus-outline', txt: '复制添加', id: 2 },
          { icon: 'el-icon-set-up', txt: '同步上级配置', id: 3 }
        ],
        visible: false,
        isNewCrad: false, // 是否新增
        newCradData: {},
        newTreeData: {},
        rawData: {}, // 上一次修改完成的数据
        initData: {}, // 初始数据
        checkTypeList: [],
        newCradList: { // 增加新数据源
          itemId: 0,
          itemName: '',
          checkType: '',
          itemType: 1,
          orgId: '',
          orgName: '',
          orgSNNo: '',
          endEdit: true,
          csmType: '',
          orderNo: '',
          detailList: [
            {
              itemDetailId: 0,
              itemDetailName: '',
              itemId: 0,
              itemName: '',
              isChecked: 1,
              itemType: 1,
              orderNo: 1
            }
          ]
        },
        isStyleId: '',
        title: '',
        btnsList: [
          { txt: '编辑', id: 1 },
          { txt: '删除', id: 2 },
          { txt: '上移', id: 3 },
          { txt: '下移', id: 4 },
          { txt: '最前', id: 5 },
          { txt: '最后', id: 6 }
        ],
        bodyStyle: {},
        cardList: [],
        tableData: {
          column: [
            {
              prop: 'itemDetailName',
              label: '选项说明'
            },
            {
              prop: 'csmName',
              label: '默认',
              render: (h, { row, $index }) => {
                return (
                  <div>
                    { row.itemType === 1 && <el-checkbox></el-checkbox>}
                    { row.itemType === 3 && <el-radio></el-radio>}
                  </div>
                )
              }
            }
          ]
        },
        orgName: '',
        orgId: '',
        initTableAttrComeFrom: 1
      }
    },
    async created() {},
    methods: {
      async open(cardVal, treeVal) {
        this.cardList = []
        this.initTableAttrComeFrom = 1
        this.newCradData = cardVal
        this.newTreeData = treeVal
        this.getDefaultData(treeVal)
        // 初始化增加数据
        this.newCradList.checkType = cardVal.id
        this.newCradList.csmType = cardVal.value
        this.newCradList.orgId = treeVal.orgId
        this.newCradList.orgName = treeVal.orgName
        this.newCradList.orgSNNo = treeVal.orgSNNo
        const { data } = await checkConfigInquire2({
          csmType: cardVal.value,
          checkType: cardVal.id,
          orgId: treeVal.orgId,
          orgName: treeVal.orgName,
          orgSNNo: treeVal.orgSNNo
        })
        if (data.length > 0) {
          this.orgName = data[0].orgName
          this.orgId = data[0].orgId
        } else {
          this.orgName = treeVal.orgName
          this.orgId = treeVal.orgId
        }
        this.title = `${cardVal.title}--->数据来源:${this.orgName}`
        const endEdit = true // 如果为false打开编辑框 如果为true关闭编辑框
        var orderNo = 0 // 排序号
        this.cardList = data.map(item => {
          orderNo++
          return { ...item, endEdit, orderNo }
        })
        this.cardList.forEach((item) => {
          if (item.itemType === -1) {
            if (item.detailList.length === 2) {
              let isChecked = ''
              item.detailList.forEach((item2) => {
                if (item2.isChecked === 2) {
                  isChecked = item2.itemDetailName
                }
              })
              const detailList = []
              item.detailList.forEach((item2) => {
                if (item2.itemDetailName === '必传') {
                  item2.isChecked = isChecked
                  detailList.push(item2)
                }
              })
              item.detailList.forEach((item2) => {
                if (item2.itemDetailName === '非必传') {
                  item2.isChecked = isChecked
                  detailList.push(item2)
                }
              })
              item.detailList = detailList
            }
          }
        })
        // this.cardList.forEach(item => {
        //   item.checkType = this.newCradData.id
        //   item.csmType = this.newCradData.value
        // })
        // 存储一份原数据
        this.rawData = this.deepClone(this.cardList)
        // 存储一份初始数据
        this.initData = this.deepClone(this.cardList)
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      async getDefaultData(treeVal) {
        const params = {
          orgId: treeVal.orgId,
          csmType: this.newCradData.value
        }
        const res = await gasCheckQueryList(params)
        this.checkTypeList = res.data
      },
      async copySave(cardVal, treeVal) {
        const { data } = await checkConfigInquire2({
          csmType: cardVal.value,
          checkType: cardVal.id,
          orgId: treeVal.orgId,
          orgName: treeVal.orgName,
          orgSNNo: treeVal.orgSNNo
        })
        const endEdit = true // 如果为false打开编辑框 如果为true关闭编辑框
        var orderNo = 0 // 排序号
        this.cardList = data.map(item => {
          orderNo++
          return { ...item, endEdit, orderNo }
        })
        this.cardList.forEach(item => {
          item.checkType = this.newCradData.id
          item.csmType = this.newCradData.value
        })
        this.cardList.forEach((item) => {
          if (item.itemType === -1) {
            if (item.detailList.length === 2) {
              let isChecked = ''
              item.detailList.forEach((item2) => {
                if (item2.isChecked === 2) {
                  isChecked = item2.itemDetailName
                }
              })
              const detailList = []
              item.detailList.forEach((item2) => {
                if (item2.itemDetailName === '必传') {
                  item2.isChecked = isChecked
                  detailList.push(item2)
                }
              })
              item.detailList.forEach((item2) => {
                if (item2.itemDetailName === '非必传') {
                  item2.isChecked = isChecked
                  detailList.push(item2)
                }
              })
              item.detailList = detailList
            }
          }
        })
        // 存储一份原数据
        this.rawData = this.deepClone(this.cardList)
        // 存储一份初始数据
        // this.initData = this.deepClone(this.cardList)
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      async success() {
        const me = this
        // 点击编辑之前判断是否有其他编辑项
        const flag = me.cardList.every(item => item.endEdit !== false)
        const isFlag = flag === true && me.newCradList.endEdit === true
        if (isFlag) {
          me.cardList.forEach((item, index) => {
            item.orgId = this.newCradList.orgId
            item.orgName = this.newCradList.orgName
            item.orgSNNo = this.newCradList.orgSNNo
            item.orderNo = index + 1
            if (item.itemType === -1) {
              if (item.detailList) {
                const isChecked = item.detailList[0].isChecked
                item.detailList.forEach((item2, index2) => {
                  if (item2.itemDetailName === '必传') {
                    item2.isChecked = isChecked === '必传' ? 2 : 1
                  }
                  if (item2.itemDetailName === '非必传') {
                    item2.isChecked = isChecked === '非必传' ? 2 : 1
                  }
                })
              }
            }
          })
          if (me.cardList.length) {
            let dateIsChange = false
            if (me.cardList.length !== me.initData.length) {
              dateIsChange = true
            } else {
              for (var x = 0; x < me.cardList.length; x++) {
                var row = me.cardList[x]
                var itemBean = me.initData[x]
                if (row.itemName !== itemBean.itemName || // 安检名称
                  row.itemId !== itemBean.itemId || // 安检id
                  row.itemType !== itemBean.itemType || // 选项类型
                  row.orderNo !== itemBean.orderNo // 排序号
                ) {
                  dateIsChange = true
                  break
                }
                // 比较安检项
                var rowList = me.cardList[x].detailList
                var detailList = itemBean.detailList
                if (rowList.length !== detailList.length) { // 说明安检选项不同
                  dateIsChange = true
                  break
                } else {
                  for (var a = 0; a < rowList.length; a++) {
                    var rowBean = rowList[a]
                    var detailBean = detailList[a]
                    if (rowBean.itemDetailName !== detailBean.itemDetailName 	|| // 选项详情名称
                      rowBean.itemDetailId !== detailBean.itemDetailId 	|| // 选项详情id
                      rowBean.isChecked !== detailBean.isChecked || // 选项状态
                      rowBean.orderNo !== detailBean.orderNo || // 选项排序号
                      rowBean.isUploadPic !== detailBean.isUploadPic || // 是否拍照取证
                      rowBean.modificationType !== detailBean.modificationType // 即查即改
                    ) {
                      dateIsChange = true
                      break
                    }
                  }
                }
                if (dateIsChange) { // 退出循环
                  break
                }
              }
            }
            if (!dateIsChange) { // 说明数据没有任何改变
              return new Promise(resolve => {
                this.resolve = resolve
                this.visible = false
              })
            }
            // 请求接口
            const { status } = await checkConfigSave(me.cardList)
            if (status === 200) {
              me.$message({
                type: 'success',
                message: '保存安检数据成功!'
              })
              return new Promise(resolve => {
                this.resolve = resolve
                this.visible = false
              })
            }
          } else {
            me.$message({
              message: '请增加安检项',
              type: 'warning'
            })
          }
        } else {
          me.$message({
            message: '存在未结束编辑的安检项',
            type: 'warning'
          })
        }
      },
      reset() {
        this.init()
      },
      handleClose() {
        this.visible = false
        var dialogBody = document.getElementsByClassName('el-dialog__body')[0]
        dialogBody.scrollTop = 0
      },
      // 按钮事件
      toPush(val, type, index) {
        const me = this
        const obj = {
          // 编辑
          1: (val) => {
            // 点击编辑之前判断是否有其他编辑项
            const flag = me.cardList.every(item => item.endEdit !== false)
            const isFlag = flag === true && me.newCradList.endEdit === true
            if (isFlag) {
              me.onBox(val)
              me.cardList.map(item => {
                val.orderNo === item.orderNo ? item.endEdit = false : item.endEdit = true
              })
              // 在下一次DOM更新循环结束之后执行回调
              me.$nextTick(() => {
                me.$refs.edittable[0].open(val)
              })
            } else {
              me.$message({
                message: '存在未结束编辑的安检项',
                type: 'warning'
              })
            }
          },
          // 删除
          2: (val) => {
            this.$confirm('删除会清除数据，是否删除？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.cardList = this.cardList.filter(item => {
                return item.orderNo !== val.orderNo
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
          },
          // 上移
          3: (val, index) => {
            if (index !== 0) {
              const topData = this.cardList[index - 1 ] // 获取上一条数据
              this.cardList[index] = topData // 把一条数据复制给当前数据
              this.cardList[index - 1] = val // 把当前数据复制给上一个数据
              this.cardList = [...this.cardList] // 从新复制数据
            }
          },
          // 下移
          4: (val, index) => {
            if (index !== this.cardList.length - 1) {
              const topData = this.cardList[index + 1 ]
              this.cardList[index] = topData
              this.cardList[index + 1] = val
              this.cardList = [...this.cardList]
            }
          },
          // 最前
          5: (val, index) => {
            if (index !== 0) {
              // const topData = this.cardList[0]
              // this.cardList[index] = topData
              // this.cardList[0] = val
              // this.cardList = [...this.cardList]
              const leftData = this.cardList.slice(0, index)
              const rightData = this.cardList.slice(index + 1)
              this.cardList = [this.cardList[index]].concat(leftData, rightData)
            }
          },
          // 最后
          6: (val, index) => {
            if (index !== this.cardList.length - 1) {
              // const topData = this.cardList[ this.cardList.length - 1 ]
              // this.cardList[index] = topData
              // this.cardList[this.cardList.length - 1] = val
              // this.cardList = [...this.cardList]
              const leftData = this.cardList.slice(0, index)
              const rightData = this.cardList.slice(index + 1)
              this.cardList = leftData.concat(rightData, [this.cardList[index]])
            }
          }
        }
        obj[type](val, index)
      },
      onPush(type) {
        const me = this
        const obj = {
          // 增加
          1: () => {
            // 点击编辑之前判断是否有其他编辑项
            const flag = me.cardList.every(item => item.endEdit !== false)
            const isFlag = flag === true && me.newCradList.endEdit === true
            if (isFlag || !me.cardList.length) {
              me.isStyleId = ''
              me.bodyStyle = {
                'border': '1px solid #617ff8',
                'box-shadow': '0px 3px 6px 0px undef'
              }
              me.isNewCrad = true
              me.newCradList.endEdit = false
              if (me.cardList.length) {
                this.newCradList.orderNo = me.cardList[ me.cardList.length - 1 ].orderNo
                this.newCradList.orderNo++
              } else {
                this.newCradList.orderNo = 1
              }

              // 在下一次DOM更新循环结束之后执行回调
              me.$nextTick(() => {
                me.$refs.edittable.open(me.deepClone(me.newCradList), me.isNewCrad, this.newTreeData)
                this.$refs.edittable.$el.scrollIntoView() // 增加元素 保持滚动条再底部
              })
            } else {
              me.$message({
                message: '存在未结束编辑的安检项',
                type: 'warning'
              })
            }
          },
          // 复制添加
          2: async() => {
            me.$refs.copyadd.open(me.newCradData, me.newTreeData, this.orgId)
          },
          // 同步上级配置
          3: async() => {
            const { status } = await checkConfigList({
              orgId: this.newTreeData.orgId,
              csmType: this.newCradData.value,
              checkType: this.newCradData.id
            })
            if (status === 200) {
              this.open(this.newCradData, this.newTreeData)
              // 重新复制初始数据
              // this.cardList = this.deepClone(this.initData)
              this.initTableAttrComeFrom = 3
            }
          }
        }
        obj[type]()
      },
      // 取消编辑
      cancelEdit(tableData, isBtnEdit) {
        this.init()
        this.cardList.map(item => item.endEdit = true)
        // 处理编辑按钮逻辑
        if (isBtnEdit) {
          this.cardList = this.cardList.filter(item => {
            return item.itemId !== tableData.itemId
          })
          // 重新复制上一次修改完成的数据
          this.rawData = this.cardList
        } else {
          // 重新复制上一次修改完成的数据
          this.cardList = this.deepClone(this.rawData)
        }
      },
      // 完成编辑
      saveEdit(obj) {
        var id = 1
        this.init()
        const flag = this.cardList.every(item => item.itemId !== obj.data.itemId)
        if (flag) {
          this.cardList.push(obj.data)
        } else {
          // 走到这里说明是新增的数据和新增的旧数据
          const flag = this.cardList.every(item => item.orderNo !== obj.data.orderNo)
          if (flag) {
            this.cardList.push(obj.data)
          }
        }
        this.cardList.map(item => {
          item.endEdit = true
          item.orderNo = id++
        })
        // 存储一份上一次修改完成的数据
        this.rawData = this.deepClone(this.cardList)
      },
      // 卡片点击
      onBox(val) {
        // 改变选中的样式
        this.isStyleId = val.orderNo
        this.bodyStyle = {
          'border': '1px solid #617ff8',
          'box-shadow': '0px 3px 6px 0px undef'
        }
      },
      // 初始化
      init() {
        this.newCradList.endEdit = true
        this.isStyleId = ''
        this.isNewCrad = false
        this.bodyStyle = {}
      },
      // 深拷贝
      deepClone(target) {
        var result
        if (typeof target === 'object') {
          if (Array.isArray(target)) {
            result = []
            for (const i in target) {
              result.push(this.deepClone(target[i]))
            }
          } else if (target === null) {
            result = null
          } else if (target.constructor === RegExp) {
            result = target
          } else {
            result = {}
            for (const i in target) {
              result[i] = this.deepClone(target[i])
            }
          }
        } else {
          result = target
        }
        return result
      },
      checkChange(value, index) {
        this.cardList[index].detailList.forEach((item, itemIndex) => {
          if (item.itemDetailName !== value) {
            item.isChecked = 0
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/.el-dialog__body {
  padding-top: 0;
  margin-top: 0;
}
.btn-col {
  position: fixed;
  z-index: 1000;
  width: 944px;
  padding-top: 20px;
  padding-bottom: 20px;
  background: #fff;
}
.ext-table {
  padding-top: 73px;
  .card-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    h2 {
      width: 45%;
      height: 20px;
      padding-left: 12px;
      margin: 0;
      overflow: hidden;
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 14px;
      font-weight: 700;
      line-height: 20px;
      color: #01999f;
      text-overflow: ellipsis;
      white-space: nowrap;
      border-left: 4px solid #01999f;
    }
  }
  .card-item-class {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 10px;
    div {
      margin-right: 10px;
    }
  }
}
.dia {
  /deep/.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color: #409EFF;
    border-color: #409EFF;
  }
  /deep/ .el-radio__input.is-disabled.is-checked .el-radio__inner {
    background: #409EFF;
    border-color: #409EFF;
  }
}
</style>
